<template>
  <div class="flex">
    <vue-header :title="title" class="com-onMask"></vue-header>
    <tab class="tabs" v-show="visibleTabs">
      <tab-item @click.native="selected = 'usedCar'" ref="usedCar">二手车</tab-item>
      <tab-item @click.native="selected = 'sign'" ref="sign">标书</tab-item>
      <tab-item @click.native="selected = 'seekCar'" ref="seekCar">人找车</tab-item>
      <tab-item @click.native="selected = 'seekPerson'" ref="seekPerson">车找人</tab-item>
      <tab-item @click.native="selected = 'find'" ref="find" v-if="!otherListMethod">我的发现</tab-item>
    </tab>

    <slot name="bar"></slot>
    <div style="padding-left: 15px;padding-right: 15px;background-color: white;padding-bottom: 5px">
    <div v-show="selected=='seekCar'|| selected=='seekPerson'" class="serach com-input-container" >
      <input type="text" v-model="search_word"  placeholder="搜索" >
      <img @click="search_info" src="@img/home/home_icon_search@2x.png" class="query"  />
    </div>
    </div>
    <div class="flex-grow flex-scroll flex" style="position:relative;">
      <transition :name="transitionName">
        <keep-alive>
          <component :is="selected" :showList="showList" ref="list" style="height:100%"
            v-if="showList.status !== 5"
            :useingComponent="useingComponent"
            :loadMethod="loadMethod"
            :onClickMethod="onClickMethod"
            :visibleMoreBtn="!otherListMethod"
            :openMoreMenuMethod="openMoreMenuMethod"
          ></component>
          <!--
            :visibleMoreBtn="!otherListMethod" 这里，如果没有otherListMethod，证明还是已发布列表，显示更多菜单
          -->

          <div class="com-notData flex-grow" title="暂无内容" v-else></div>
        </keep-alive>
      </transition>
    </div>
  </div>
</template>

<script>
import { Tab, TabItem } from 'vux'
import List from './List'
import saveScroll from '@u/mixin/saveScroll.js'
/**
 * 该页思路：通过selected选择要使用的数据、方法、组件，再交给List组件渲染
 * 同时，这个页面【还是收藏列表和咨询列表，以及5个全部列表的模板组件】。
 * 通过otherListMethod参数确定是否被用作模板显示收藏列表或咨询列表，
 * 这时“我的发现将被隐藏”，otherListMethod传入一个函数，该函数返回一个返回接口数据的延迟对象。title控制标题文字
 *
 *
 * 当作为全部列表的模板组件时，设置visibleTabs参数隐藏tabs，传入defaultSelected区分列表，并设置title
 */
function createListWatcherData(){
  return {
    data: null,
    page: 1,
    pageTotal: 1,
    status: 1
  }
}

export default {
  components: {
    Tab,
    TabItem,

    // 使用一个组件对象创造5个列表组件
    UsedCar: List,
    Sign: List,
    SeekCar: List,
    SeekPerson: List,
    Find: List
  },

  props: {
    otherListMethod: {},
    title: {
      default: '已发布'
    },
    visibleTabs: {
      default: true
    },
    defaultSelected: {
      default: 'usedCar'
    },
    isAllList: {
      default: false
    }
  },

  mixins: [saveScroll],

  data (){
    return {
      search_word:'',
      selected: this.defaultSelected,
      cache: {
        usedCar: createListWatcherData(),
        sign: createListWatcherData(),
        seekCar: createListWatcherData(),
        seekPerson: createListWatcherData(),
        find: createListWatcherData()
      },
      transitionName: 'move-in'
    }
  },

  mounted (){
    // 首次进入选中第一项
    this.$refs[this.selected].$el.click()
    this.loadMethod()
  },

  computed: {
    // 要使用的对应数据
    showList (){
      return this.cache[this.selected]
    },

    // 要使用的对应方法
    loadMethod (){
      return {
        usedCar: isSwipeDownRefresh => this.loadData('usedCar', '0,2,3,5', isSwipeDownRefresh),
        sign: isSwipeDownRefresh => this.loadData('sign', '', isSwipeDownRefresh),
        seekCar: isSwipeDownRefresh => this.loadData('seekCar', '0', isSwipeDownRefresh),
        seekPerson: isSwipeDownRefresh => this.loadData('seekPerson', '0', isSwipeDownRefresh),
        find: isSwipeDownRefresh => this.loadData('find', '0', isSwipeDownRefresh)
      }[this.selected]
    },

    // 要使用的list项被点击后调用的方法
    onClickMethod (){
      return {
        usedCar: id => this.$toView('info/usedCar', { query: { id } }),
        sign: id => this.$toView('info/sign', { query: { id } }),
        seekCar: id => this.$toView('info/seek', { query: { id, type: 2 } }),
        seekPerson: id => this.$toView('info/seek', { query: { id } }),
        find: id => this.$toView('info/find', { query: { id } })
      }[this.selected]
    },

    // 要使用的item组件名
    useingComponent (){
      return {
        usedCar: 'CarInfoItem',
        sign: 'SignItem',
        seekCar: 'SeekCarItem',
        seekPerson: 'SeekPersonItem',
        find: 'FindItem'
      }[this.selected]
    },

    openMoreMenuMethod (){
      return id =>{
        this.$alert.actionSheet([
          {
            label: '删除',
            value: 'del'
          }
        ]).then(action =>{
          return {
            del: () =>{
              var apiName = this.selected.indexOf('seek') >= 0 ? 'seek' : this.selected
              this.$alert.confirm('确定要删除该条吗？')
              .then(() => _api(`${apiName}/delete`, { id }))
              .then(() =>{
                var delIndex = ''
                this.showList.data.some((val, ind) =>{
                  if(val.id === id) delIndex = ind
                })

                this.showList.data.splice(delIndex, 1)
                if(!this.showList.data.length) this.showList.status = 5
                this.$alert.toast('删除成功', 'success')
              })
            }
          }[action]()
        })
      }
    }
  },

  watch: {
    selected (newVal, oldVal){
      this.loadMethod()

      // 保存当前滚动条位置
      this.$refs.list && this.$refs.list.getScrollViewVNode().saveScroll()

      // 等待视图改变，读取滚动条位置
      this.$nextTick(() => this.$refs.list && this.$refs.list.getScrollViewVNode().loadSavedScroll())

      var order = {
        usedCar: 0,
        sign: 1,
        seekCar: 2,
        seekPerson: 3,
        find: 4
      }

      this.transitionName = order[newVal] > order[oldVal] ? 'move-in' : 'move-out'
    },

    // 每次从“我的”页面或首页(用作全部列表的模板组件时)进入时，重新加载列表
    $route (to, from){
      if(
        (from.name === 'index/my' && to.name === 'publishedList') ||
        (from.name === '/' && /allList\/^(usedCar|signs|seekCar|seekPerson|finds)$/.test(to.name))
      ){
        this.reload()
      }
    }
  },

  methods: {
    // 初始化，用于清空列表
    init (){
      this.cache = {
        usedCar: createListWatcherData(),
        sign: createListWatcherData(),
        seekCar: createListWatcherData(),
        seekPerson: createListWatcherData(),
        find: createListWatcherData()
      }
    },
      search_info(){
          this.$parent.search_info(this.search_word);
      },

    reload (){
      this.init()
      this.loadMethod()
    },

    // 读取数据
    loadData (type, level = '', isSwipeDownRefresh){
      return new Promise((resolve, reject) =>{
        this.$alert.loading.show()
        _locationReady.then(() =>{
          this.$alert.loading.hide()
          if(this.cache[type].page <= this.cache[type].pageTotal || isSwipeDownRefresh){
            if(!isSwipeDownRefresh) this.cache[type].status = 2

            var apiType = type
            var seek_type = ''
            if(type === 'seekCar'){
              apiType = 'seek'
              seek_type = 2
            }
            if(type === 'seekPerson'){
              apiType = 'seek'
              seek_type = 1
            };(() =>{
              if(this.otherListMethod){
                return this.otherListMethod(type, this.cache[type].page, isSwipeDownRefresh)
              }else{
                return _api(`${apiType}/getListByCon`, {
                  level,
                  seek_type,
                  page: isSwipeDownRefresh ? 1 : this.cache[type].page,
                  ...(!this.isAllList ? { user_id: localStorage.getItem('user_id') } : {}),
                })
              }
            })().then(data =>{

                  this.cache[type].status = data.current_page >= data.last_page ? 4 : 3
              if(!this.cache[type].data) this.cache[type].data = []
              this.cache[type].data = (isSwipeDownRefresh ? [] : this.cache[type].data).concat(data.data)
              this.cache[type].page = data.current_page
              this.cache[type].pageTotal = data.last_page|| 1
              this.cache[type].page++
              if(this.cache[type].pageTotal === 1 && !this.cache[type].data.length){
                this.cache[type].status = 5
              }
                 console.log("-------------"+JSON.stringify(this.cache[type].status))
              resolve()
            }).catch(() =>{
              this.cache[type].status = 0
              reject()
            })
          }else{
            this.cache[type].status = this.cache[type].data.length ? 4 : 5
            resolve()
          }
        })
      })
    },
  }
}
</script>

<style lang="less" scoped>
.tabs{
  margin-top: 5px;
}
.serach{
  height: 30px;
  background:#f4f4f4;
  border-radius: 15px;
  padding-left: 20px;
  font-size: 14px;
  position: relative;

  input::-webkit-input-placeholder{
    color: #666;
  }


}
.query{
  content: '';
  width: 18px;
  height: 18px;
  background-repeat: no-repeat;
  background-size: 100%;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}
</style>
